//
//  HFTabbar.swift
//  HFWeChat
//
//  Created by 黄来峰 on 16/4/17.
//  Copyright © 2016年 itcast. All rights reserved.
//



import UIKit


protocol HFTabBarDelegate:NSObjectProtocol{
    
    func presentViewController()
    
}

class HFTabbar: UITabBar {
    
   //声明一个代理
   weak var tabbarDelegate:HFTabBarDelegate?
    
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
    }
    //这个方法在重写init的时候必须实现
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //重写Layout方法添加控件
    override func layoutSubviews() {
        super.layoutSubviews()
        //为每个控件设置frame
        let width = kSCREENW / 5
        var index: CGFloat = 0
        //遍历TabBar
        for value in self.subviews{
        
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                //先判断是不是tabbar得子控件，如果是，那就设置tabbar子控件的frame
                value.frame.origin.x = width * index
                //设置每个控件的宽度
                value.bounds.size.width = width
                
                index++
                if index == 2{
                    index++
                }
            }
            composeButton.center.x = self.bounds.size.width * 0.5
            composeButton.center.y = self.bounds.size.height * 0.5
        }
    }
    
    private lazy var composeButton: UIButton = {
        //创建一个Button
        let button = UIButton()
        //为Button增加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        //设置Button的正常状态下背景的图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        //设置Button在高亮状态下的背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //为Button添加图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
        return button
        
    }()
    
  @objc private func composeButtonClick(){
    
    self.tabbarDelegate?.presentViewController()
    
    
    }
    
    
}
